<!--
 * @Author: your name
 * @Date: 2020-12-29 19:30:17
 * @LastEditTime: 2020-12-31 11:38:41
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \H5 2010 studyd:\H5 2010 练习\第三阶段 Vue + node\DAY 7\panda\src\views\category\subCategory.vue
-->
<template>
<div id="SubCategory">
  <van-grid :column-num="3" :gutter="5">
    <van-grid-item
      v-for="category in categories"
      :key="category.id"
      :icon="category.imageUrl"
      :text="category.title"
    />
</van-grid>
</div>
</template>

<script>
import { getSubCategories } from '@/api/category'

export default {
  name: 'SubCategory',
  data() {
    return {
      categories: []
    }
  },
  // created() {
  //   console.log('created: ', this.$route)
  // },

  // watch: { // 监视激活路由的变化，当路由改变，则查询子分类数据
  //   $route: {
  //     handler(v) {
  //       // 获取父级分类的 id
  //       const { cid } = v.params
  //       // 查询子分类数据
  //       getSubCategories(cid)
  //         .then(res => {
  //           // console.log('子分类：', res)
  //           this.categories = res.categories
  //         })
  //     },
  //     immediate: true
  //   }
  // }

  // 除了用 watch 还可以用 导航守卫
  beforeRouteEnter(to, from, next) {
    console.log('enter')
    next(vm => {
      // 获取父级分类的 id
      const { cid } = to.params
      // 查询子分类数据
      getSubCategories(cid)
        .then(res => {
          // console.log('子分类：', res)
          vm.categories = res.categories
        })
    })
  },
  beforeRouteUpdate(to, from, next) {
    console.log('update')
    // 获取父级分类的 id
    const { cid } = to.params
    // 查询子分类数据
    getSubCategories(cid)
      .then(res => {
        // console.log('子分类：', res)
        this.categories = res.categories
      })
    next()
  },
  beforeRouteLeave(to, from, next) {
    console.log('leave')
    next()
  }
}
</script>

<style lang="scss" scoped>

</style>
